package com.sd.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

import com.alex.http.AGetReuqest;
import com.alex.http.AHandledResult;
import com.alex.http.AHttpEngine;
import com.alex.http.AHttpListener;
import com.alex.log.ALog;
import com.mobclick.android.MobclickAgent;
import com.sd.database.BetaReadDao;
import com.sd.view.DoubanHandler;
import com.sd.view.HistoryAdpater;

/**
 * 
 * @author Alex.Lu
 * 
 */
public class SreachActivity extends BaseActivity implements OnClickListener, AHttpListener, OnItemClickListener, TextWatcher, OnEditorActionListener {

	private int[] COLORS = {0xffff0000,0xff00ff00,0xff0000ff,0xffffff00,0xffff00ff,0xff00ffff};
	private String[] strs = {"中医扬名","光明纪元","神剑永恒","神印王座","天才相师","吞噬星空","材料为王","锦衣夜行","全职高手"};
	private boolean mFlag;
	private Button mHreachHotBT;
	private Button mSreachHistoryBT;
	private ImageButton mSearchTwo;
	private ImageButton mSearchVoice;
	private ViewFlipper mFlipper;
	private ListView mHistoryList;
	private Button mCancelBT;
	private EditText mText;
	private ImageButton mSearchBT;
	private HistoryAdpater mHistoryAdapter;
	
	private Vector<String> historys;
	private RelativeLayout mHotWords;
	
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		//((BetaReadApp)this.getApplication()).createExitDialog();
		 createExitDialog();
	}
	
	/**
	 * 是否退出客户端的对话框
	 */
	public void createExitDialog() {
		Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage(getString(R.string.msg_exit)).setPositiveButton(
				R.string.btn_ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						System.exit(0);
					}
				}).setNegativeButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_sreach);
		
		mFlag = true;
		mFlipper = (ViewFlipper) findViewById(R.id.search_flipper);
		mHreachHotBT = (Button) findViewById(R.id.sreach_hot);
		mHreachHotBT.setOnClickListener(this);
		mSreachHistoryBT = (Button) findViewById(R.id.sreach_history);
		mSreachHistoryBT.setOnClickListener(this);
		mSearchTwo = (ImageButton) findViewById(R.id.search_two);
		mSearchTwo.setOnClickListener(this);
		mSearchVoice = (ImageButton) findViewById(R.id.search_voice);
		mSearchVoice.setOnClickListener(this);
		mHistoryList = (ListView) findViewById(R.id.historyList);
		historys = BetaReadDao.querySearchItems(this);
		mHistoryAdapter = new HistoryAdpater(this, historys);
		mHistoryList.setAdapter(mHistoryAdapter);
		mHistoryList.setOnItemClickListener(this);
		mText = (EditText)findViewById(R.id.search_et);
		mText.setOnEditorActionListener(this);
		mText.addTextChangedListener(this);
		mCancelBT = (Button)findViewById(R.id.nosreach);
		mCancelBT.setOnClickListener(this);
		mCancelBT.setVisibility(View.GONE);
		
		mSreachHistoryBT.setSelected(false);
		mHreachHotBT.setSelected(true);
		mHotWords = (RelativeLayout)findViewById(R.id.hot_words);
		
		Button hot1 = (Button)findViewById(R.id.hotword1);
		hot1.setText(strs[0]);
		hot1.setTag(strs[0]);
		hot1.setOnClickListener(this);
		Button hot2 = (Button)findViewById(R.id.hotword2);
		hot2.setText(strs[1]);
		hot2.setTag(strs[1]);
		hot2.setOnClickListener(this);
		Button hot3 = (Button)findViewById(R.id.hotword3);
		hot3.setText(strs[2]);
		hot3.setTag(strs[2]);
		hot3.setOnClickListener(this);
		Button hot4 = (Button)findViewById(R.id.hotword4);
		hot4.setText(strs[3]);
		hot4.setTag(strs[3]);
		hot4.setOnClickListener(this);
		Button hot5 = (Button)findViewById(R.id.hotword5);
		hot5.setText(strs[4]);
		hot5.setTag(strs[4]);
		hot5.setOnClickListener(this);
		Button hot6 = (Button)findViewById(R.id.hotword6);
		hot6.setText(strs[5]);
		hot6.setTag(strs[5]);
		hot6.setOnClickListener(this);
		Button hot7 = (Button)findViewById(R.id.hotword7);
		hot7.setText(strs[6]);
		hot7.setTag(strs[6]);
		hot7.setOnClickListener(this);
		Button hot8 = (Button)findViewById(R.id.hotword8);
		hot8.setText(strs[7]);
		hot8.setTag(strs[7]);
		hot8.setOnClickListener(this);
		
		mSearchBT = (ImageButton)findViewById(R.id.search_bt);
		mSearchBT.setOnClickListener(this);
		
		 PackageManager pm = getPackageManager();
	        List<ResolveInfo> activities = pm.queryIntentActivities(
	                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
	        if (activities.size() != 0) {
	        	mSearchVoice.setOnClickListener(this);
	        } else {
	        	mSearchVoice.setEnabled(false);
	        }
	        
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		int v_id = v.getId();
		switch (v_id) {
		case R.id.search_bt:
			InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			String text = mText.getText().toString();
			if(text!=null || text.trim().equals("") ){
				historys.add(0,text);
				if(historys.size()>10){
					historys.remove(10);
				}
				BetaReadDao.insertSearch(this, text);
				mHistoryAdapter.notifyDataSetChanged();
			}
			
			((TabActivity)this.getParent()).getTabHost().setCurrentTab(1);
			BookStoreActivity.search(text);
			mText.clearFocus();
			break;
		case R.id.sreach_hot:
			if(!mFlag){
				mSreachHistoryBT.setSelected(false);
				mHreachHotBT.setSelected(true);
				mFlipper.showNext();
				mFlag=!mFlag;
			}
			break;
		case R.id.nosreach:
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
			mCancelBT.setVisibility(View.GONE);
			mText.setText("");
			mText.clearFocus();
			break;
		case R.id.sreach_history:
			if(mFlag){
				mSreachHistoryBT.setSelected(true);
				mHreachHotBT.setSelected(false);
				mFlipper.showPrevious();
				mFlag=!mFlag;
			}
			break;
		case R.id.search_two:
			 intent = new Intent();  
			 intent.setClass(this, CaptureActivity.class);
			 startActivityForResult(intent, TWO_REQUEST_CODE);
			/*String url = "http://api.douban.com/book/subject/2023013?apikey=00de989655b54755029bc9c3011fd5ff";
			AGetReuqest getOperation = new AGetReuqest(10,url,this,new DoubanHandler(),null);
			AHttpEngine.getInstance().request(getOperation);*/
			break;
		case R.id.search_voice:
			//通过Intent传递语音识别的模式,开启语音  
            intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
            //语言模式和自由形式的语音识别  
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.  
                            LANGUAGE_MODEL_FREE_FORM);  

            //提示语音开始  
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"开始语音");  
            //开始执行我们的Intent、语音识别  
            startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
			break;
			
		case R.id.hotword1:
		case R.id.hotword2:
		case R.id.hotword3:
		case R.id.hotword4:
		case R.id.hotword5:
		case R.id.hotword6:
		case R.id.hotword7:
		case R.id.hotword8:
			
			String text1 = (String)v.getTag();
			((TabActivity)this.getParent()).getTabHost().setCurrentTab(1);
			BookStoreActivity.search(text1);
			break;
		default:
			break;
		}
	}
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 4321;  
	private static final int TWO_REQUEST_CODE = 1234;
	//当语音结束时的回调函数onActivityResult  
	@Override 
	protected void onActivityResult(int requestCode,int resultCode,Intent data)  
	{  
	    // 判断是否是我们执行的语音识别  
	    if(requestCode==VOICE_RECOGNITION_REQUEST_CODE&&resultCode==RESULT_OK)  
	    {  
	        // 取得语音的字符  
	        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);  
	        //设置视图更新  
	        //mList.setAdapter(new ArrayAdapter<String>(this,android.  R.layout.simple_list_item_1,results));  
	        String resultsString = "";   
	        for (int i = 0; i < results.size(); i++)  
	        {  
	            resultsString += results.get(i);  
	        }
	        mText.setText(results.get(0));
	        
	        Toast.makeText(this,resultsString,Toast.LENGTH_LONG).show();   
	        super.onActivityResult(requestCode, resultCode, data);  
	    } else  if(requestCode==TWO_REQUEST_CODE&&resultCode==RESULT_OK) {
	    	String text = data.getStringExtra(CaptureActivity.CODE_REQUEST);
	    	StringBuffer sbuf = new StringBuffer();
	    	sbuf.append("http://api.douban.com/book/subject/isbn/");
	    	sbuf.append(text);
	    	sbuf.append("?apikey=00de989655b54755029bc9c3011fd5ff");
	    	ALog.e(sbuf.toString());
			AGetReuqest getOperation = new AGetReuqest(10,sbuf.toString(),this,new DoubanHandler(),null);
			AHttpEngine.getInstance().request(getOperation);
	    }
	}

	@Override
	public void onError(long arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		ALog.e("erorr!!");
	}
	
	
	@Override
	public void onResult(long arg0, Bundle arg1, AHandledResult arg2) {
		// TODO Auto-generated method stub
		ALog.e((String)arg2.mObj);
		mText.setText((String)arg2.mObj);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		String text = (String)parent.getItemAtPosition(position);
		((TabActivity)this.getParent()).getTabHost().setCurrentTab(1);
		BookStoreActivity.search(text);
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		if(s != null&& s.toString().equals("")){
			mCancelBT.setVisibility(View.GONE);
		}else{
			mCancelBT.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}  
	
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		// TODO Auto-generated method stub
		switch(actionId){  
        case EditorInfo.IME_ACTION_SEARCH:
        	InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        	String text = mText.getText().toString();
			if(text!=null || text.trim().equals("") ){
				historys.add(0,text);
				if(historys.size()>10){
					historys.remove(10);
				}
				BetaReadDao.insertSearch(this, text);
				mHistoryAdapter.notifyDataSetChanged();
			}
			
			((TabActivity)this.getParent()).getTabHost().setCurrentTab(1);
			BookStoreActivity.search(text);
			mText.clearFocus();
            break;  
        }  
		return false;
	}
}